import axios from 'axios';
import QRCode from 'qrcode';

// 微信开放平台配置
interface WeChatConfig {
  appId: string;
  appSecret: string;
  redirectUri: string;
}

// 微信扫码登录状态
interface WeChatLoginSession {
  state: string;
  qrCode: string;
  expiresAt: number;
  status: 'pending' | 'scanned' | 'confirmed' | 'expired';
  userInfo?: {
    openid: string;
    nickname: string;
    headimgurl: string;
  };
}

// 微信用户信息接口
export interface WeChatUserInfo {
  openid: string;
  nickname: string;
  headimgurl: string;
  unionid?: string;
}

// 微信扫码登录请求接口
export interface WeChatLoginRequest {
  state?: string;
}

// 微信扫码登录响应接口
export interface WeChatLoginResponse {
  success: boolean;
  message: string;
  data?: {
    qrCode: string;
    state: string;
    expiresIn: number;
  };
}

// 微信扫码状态检查响应接口
export interface WeChatStatusResponse {
  success: boolean;
  message: string;
  data?: {
    status: string;
    userInfo?: WeChatUserInfo;
    token?: string;
  };
}

// 配置（生产环境应从环境变量获取）
const wechatConfig: WeChatConfig = {
  appId: process.env.WECHAT_APP_ID || 'your_wechat_app_id',
  appSecret: process.env.WECHAT_APP_SECRET || 'your_wechat_app_secret',
  redirectUri: process.env.WECHAT_REDIRECT_URI || 'http://localhost:3232/api/auth/wechat/callback'
};

// 存储扫码登录会话（生产环境应使用 Redis）
const loginSessions = new Map<string, WeChatLoginSession>();

// 生成随机状态码
function generateState(): string {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}

// 生成微信授权 URL
function generateWeChatAuthUrl(state: string): string {
  const params = new URLSearchParams({
    appid: wechatConfig.appId,
    redirect_uri: encodeURIComponent(wechatConfig.redirectUri),
    response_type: 'code',
    scope: 'snsapi_login',
    state: state
  });
  
  return `https://open.weixin.qq.com/connect/qrconnect?${params.toString()}#wechat_redirect`;
}

// 生成二维码
async function generateQRCode(url: string): Promise<string> {
  try {
    const qrCodeDataURL = await QRCode.toDataURL(url, {
      width: 300,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    });
    return qrCodeDataURL;
  } catch (error) {
    console.error('生成二维码失败:', error);
    throw new Error('生成二维码失败');
  }
}

// 通过 code 获取 access_token
async function getAccessToken(code: string): Promise<{ access_token: string; openid: string }> {
  try {
    const response = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
      params: {
        appid: wechatConfig.appId,
        secret: wechatConfig.appSecret,
        code: code,
        grant_type: 'authorization_code'
      }
    });

    if (response.data.errcode) {
      throw new Error(`获取 access_token 失败: ${response.data.errmsg}`);
    }

    return {
      access_token: response.data.access_token,
      openid: response.data.openid
    };
  } catch (error) {
    console.error('获取 access_token 失败:', error);
    throw new Error('获取 access_token 失败');
  }
}

// 获取微信用户信息
async function getWeChatUserInfo(accessToken: string, openid: string): Promise<WeChatUserInfo> {
  try {
    const response = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
      params: {
        access_token: accessToken,
        openid: openid,
        lang: 'zh_CN'
      }
    });

    if (response.data.errcode) {
      throw new Error(`获取用户信息失败: ${response.data.errmsg}`);
    }

    return {
      openid: response.data.openid,
      nickname: response.data.nickname,
      headimgurl: response.data.headimgurl,
      unionid: response.data.unionid
    };
  } catch (error) {
    console.error('获取用户信息失败:', error);
    throw new Error('获取用户信息失败');
  }
}

// 创建微信扫码登录会话
export async function createWeChatLoginSession(customState?: string): Promise<WeChatLoginResponse> {
  try {
    const state = customState || generateState();
    const authUrl = generateWeChatAuthUrl(state);
    const qrCode = await generateQRCode(authUrl);
    
    // 创建登录会话，5分钟过期
    const session: WeChatLoginSession = {
      state,
      qrCode,
      expiresAt: Date.now() + 5 * 60 * 1000, // 5分钟
      status: 'pending'
    };
    
    loginSessions.set(state, session);
    
    // 清理过期会话
    cleanupExpiredSessions();
    
    return {
      success: true,
      message: '二维码生成成功',
      data: {
        qrCode,
        state,
        expiresIn: 300 // 5分钟
      }
    };
  } catch (error) {
    console.error('创建微信登录会话失败:', error);
    return {
      success: false,
      message: '创建登录会话失败'
    };
  }
}

// 检查扫码登录状态
export function checkWeChatLoginStatus(state: string): WeChatStatusResponse {
  const session = loginSessions.get(state);
  
  if (!session) {
    return {
      success: false,
      message: '登录会话不存在或已过期'
    };
  }
  
  if (Date.now() > session.expiresAt) {
    session.status = 'expired';
    loginSessions.delete(state);
    return {
      success: false,
      message: '登录会话已过期'
    };
  }
  
  return {
    success: true,
    message: '状态检查成功',
    data: {
      status: session.status,
      userInfo: session.userInfo
    }
  };
}

// 处理微信授权回调
export async function handleWeChatCallback(code: string, state: string): Promise<WeChatStatusResponse> {
  try {
    const session = loginSessions.get(state);
    
    if (!session) {
      return {
        success: false,
        message: '登录会话不存在'
      };
    }
    
    if (Date.now() > session.expiresAt) {
      session.status = 'expired';
      loginSessions.delete(state);
      return {
        success: false,
        message: '登录会话已过期'
      };
    }
    
    // 更新状态为已扫描
    session.status = 'scanned';
    
    // 获取 access_token
    const { access_token, openid } = await getAccessToken(code);
    
    // 获取用户信息
    const userInfo = await getWeChatUserInfo(access_token, openid);
    
    // 更新会话状态
    session.status = 'confirmed';
    session.userInfo = userInfo;
    
    return {
      success: true,
      message: '微信登录成功',
      data: {
        status: 'confirmed',
        userInfo
      }
    };
  } catch (error) {
    console.error('处理微信回调失败:', error);
    return {
      success: false,
      message: '微信登录失败'
    };
  }
}

// 清理过期会话
function cleanupExpiredSessions(): void {
  const now = Date.now();
  for (const [state, session] of loginSessions.entries()) {
    if (now > session.expiresAt) {
      loginSessions.delete(state);
    }
  }
}

// 获取微信用户信息（用于已确认的登录）
export function getWeChatUserByState(state: string): WeChatUserInfo | null {
  const session = loginSessions.get(state);
  
  if (!session || session.status !== 'confirmed' || !session.userInfo) {
    return null;
  }
  
  return session.userInfo;
}

// 清理指定状态的会话
export function clearWeChatSession(state: string): void {
  loginSessions.delete(state);
}
